package com.cicoding.utlis;

import java.sql.*;
import java.util.Properties;

public class JdbcUtils {
    private static final String driver = "com.mysql.cj.jdbc.Driver";
    private static final String url ="jdbc:mysql://127.0.0.1:3306/kufangdemo?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
    private static final String name ="root";
    private static final String password = "etoak";

    static {
        try {
            Properties p = new Properties();
            Class.forName(driver);
        } catch (ClassNotFoundException  e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取数据库连接对象
     * @return 数据库连接对象
     * @throws Exception 获取失败
     */
    public static Connection getConnect() throws Exception {
        return DriverManager.getConnection(url, name, password);
    }

    /**
     * 关闭数据库相关资源
     * @param conn 数据库连接对象
     * @param ps sql语句执行对象
     * @param rs 查询结果集
     */
    public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
        try {
            if (conn != null) conn.close();
            if (ps != null) ps.close();
            if (rs != null) rs.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭数据库相关资源
     * @param conn 数据库连接对象
     * @param ps sql语句执行对象
     */
    public static void close(Connection conn, PreparedStatement ps) {
        close(conn, ps, null);
    }

    /**
     * 关闭数据库相关资源
     * @param conn 数据库连接对象
     * @param rs 查询结果集
     */
    public static void close(Connection conn, ResultSet rs) {
        close(conn, null, rs);
    }
}
